package com.cw.jeeyt.service.impl.process;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cw.jeeyt.service.converter.process.ProcessLeaveConverter;
import com.cw.jeeyt.service.intf.process.FlowTaskService;
import com.cw.jeeyt.service.intf.process.LeaveService;
import com.google.common.collect.Maps;
import com.cw.jeeyt.common.StringUtils;
import com.cw.jeeyt.common.utils.process.FlowableUtils;
import com.cw.jeeyt.service.bo.process.ProcessLeaveBo;
import com.cw.jeeyt.service.bo.security.SecurityUserBo;
import com.cw.jeeyt.core.util.SessionUtil;
import com.cw.jeeyt.dao.intf.process.ProcessLeaveDao;
import com.cw.lang.common.log.Log;
import com.cw.lang.common.log.TenantLog;
import com.cw.lang.common.utils.SequenceTool;

@Service
@Transactional(readOnly = true)
public class LeaveServiceImpl implements LeaveService {
    private Log logger = TenantLog.getLogger(this.getClass());
    @Autowired
    private FlowTaskService actTaskService;
    @Autowired
    private ProcessLeaveDao leaveDao;

    @Transactional(readOnly = false)
    @Override
    public String save(ProcessLeaveBo leave, Map<String, Object> variables) throws Exception {
        String businessTable = FlowableUtils.getBusinessTable("leave");
        if (StringUtils.isBlank(businessTable)) {
            return "流程启动失败，请先设置业务表";
        }
        SecurityUserBo securityUser = SessionUtil.getSessionUser();
        // 申请发起 保存业务数据
        if (StringUtils.isBlank(leave.getId())) {
            leave.setId(SequenceTool.nextId());
            leave.setCreateBy(securityUser.getId());
            leave.setUpdateBy(securityUser.getId());
            leave.setCreateDate(new Date());
            leave.setUpdateDate(new Date());
            leave.setDelFlag("0");
            leaveDao.insert(ProcessLeaveConverter.bo2Do(leave));
            String procIns = actTaskService.startProcess("leave", businessTable, leave.getId(), variables);

            logger.debug("流程已启动，流程ID：" + procIns);

            return "流程已启动，流程ID：" + procIns;
        } else {
            leave.setUpdateBy(securityUser.getId());
            leave.setUpdateDate(new Date());
            leaveDao.update(ProcessLeaveConverter.bo2Do(leave));
            leave.getAct()
                .setComment(leave.getAct()
                    .isPass() ? "[重申] " : "[销毁] " + leave.getAct()
                    .getComment());
            // 完成流程任务
            variables.put("auditPass", leave.getAct()
                .isPass());
            actTaskService.complete(leave.getAct()
                .getTaskId(), leave.getAct()
                .getProcInsId(), leave.getAct()
                .getComment(), variables);
            return "流程已" + (leave.getAct()
                .isPass() ? "[重申] " : "[销毁] ");
        }
    }

    /**
     * 审核审批保存
     *
     * @param leave
     */
    @Transactional(readOnly = false)
    @Override
    public String auditSave(ProcessLeaveBo leave) throws Exception {

        // 设置意见
        leave.getAct()
            .setComment((leave.getAct()
                .isPass() ? "[同意] " : "[驳回] ") + leave.getAct()
                .getComment());
        SecurityUserBo securityUser = SessionUtil.getSessionUser();
        leave.setUpdateBy(securityUser.getId());
        leave.setUpdateDate(new Date());
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = leave.getAct()
            .getTaskDefKey();

        Map<String, Object> vars = Maps.newHashMap();
        // 部门领导审批
        if ("deptLeaderAudit".equals(taskDefKey)) {
            leave.setDeptLeadText(leave.getAct()
                .getComment());
            leaveDao.updateLeadText(ProcessLeaveConverter.bo2Do(leave));
        }
        // HR审批
        else if ("hrAudit".equals(taskDefKey)) {
            leave.setHrText(leave.getAct()
                .getComment());
            leaveDao.updateHRText(ProcessLeaveConverter.bo2Do(leave));
        }
        // 重新修改
        else if ("modifyApply".equals(taskDefKey)) {
            leaveDao.update(ProcessLeaveConverter.bo2Do(leave));
        }

        // 未知环节，直接返回
        else {
            return "未知环节";
        }

        vars.put("auditPass", leave.getAct()
            .isPass());

        // 提交流程任务
        actTaskService.complete(leave.getAct()
            .getTaskId(), leave.getAct()
            .getProcInsId(), leave.getAct()
            .getComment(), vars);
        return "处理成功";
    }

}
